﻿using System.Data;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DotNetNuke.Common;
using System.Collections.Generic;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;
using DotNetNuke.Security.Permissions;
using IB.Common.Entities;
using System;


namespace IB.Common.Base
{
    /// <summary>
    /// Lưu cả ảnh đại diện album và ảnh đại diện album vào Album
    /// danh mục của cả News và Products vào Category
    /// Ảnh của cả tin tức
    /// </summary>
    public enum LocationImage
    {
        News, Album, Slide, Product,Category
    }

    public class V_Base : DotNetNuke.Entities.Modules.PortalModuleBase
    {
        private static VCDataDataContext data = null;
        public static VCDataDataContext Data
        {
            get
            {
                if (Null.IsNull(data)) data = new VCDataDataContext(Config.GetConnectionString());
                return data;
            }
        }

        public int TabForward
        {
            get
            {
                int _tabfwTemp = TabId;
                if (Settings["TabForward"] != null)
                {
                    if (!int.TryParse(Settings["TabForward"].ToString(), out _tabfwTemp))
                    {
                        _tabfwTemp =TabId;
                    }
                }
                return _tabfwTemp;
            }
        }

        /// <summary>
        /// Su dung khi Load Control dong 
        /// truong hop load dong control trong UI List Product, hoac News
        /// </summary>
        //public int TabPager {
        //    get {
        //        return  TabId;
        //    }
        //}

        public string WriteUrl(string tabid, string detail, string newid, string title)
        {

            int _tabid;
            int.TryParse(tabid, out _tabid);
            string url = DotNetNuke.Common.Globals.NavigateURL(_tabid == 0 ? this.TabId : _tabid,"", detail, newid, "title=" + WriteString(title));
            return url;
        }

        public string WriteString(string str)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            str = System.Text.RegularExpressions.Regex.Replace(str, "Đ|đ|&#273;|&#272;", "d", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            str = str.Normalize(System.Text.NormalizationForm.FormKD);
            for (int i = 0; i < str.Length; i++)
            {
                if (char.IsWhiteSpace(str[i])) sb.Append('-');
                else if (char.GetUnicodeCategory(str[i]) != System.Globalization.UnicodeCategory.NonSpacingMark
                    && !char.IsPunctuation(str[i])
                    && !char.IsSymbol(str[i]))
                    sb.Append(str[i]);
            }
            return sb.ToString();

        }        //thiet lap nay dung cho khi su ly tu fil Handler.ashx
        private string _homeDirectoryPortal="";
        public string HomeDirectoryPortal {

            get {
                if (string.IsNullOrEmpty(_homeDirectoryPortal)) _homeDirectoryPortal = PortalSettings.HomeDirectory;
                return _homeDirectoryPortal;
            }
            set {
                _homeDirectoryPortal = value;
            }
        }

        private string _homeDirectoryPortalFolder = "";
        public string HomeDirectoryPortalFolder
        {

            get
            {
                if (string.IsNullOrEmpty(_homeDirectoryPortalFolder)) _homeDirectoryPortalFolder = PortalSettings.HomeDirectoryMapPath;
                return _homeDirectoryPortalFolder;
            }
            set
            {
                _homeDirectoryPortalFolder = value;
            }
        }

        public string WriteUrlCat(int tabid,string catparam) {
            return DotNetNuke.Common.Globals.NavigateURL(tabid, "",catparam);
        }

        private int PageSizeDefault
        {
            get
            {
                return 10;
            }
        }

        
        public int PageSize
        {
            get
            {
                int _size = PageSizeDefault;
                if (Settings["PageSize"] != null)
                {
                    if (!int.TryParse(Settings["PageSize"].ToString(), out _size)||_size<1)
                    {
                        _size = PageSizeDefault;
                    }
                }
                return _size;
            }
        }

        public int PageCurr
        {
            get
            {
                int currentPage = Request["page"] == null ? 1 : int.Parse(Request["page"].ToString());
                return currentPage;
            }
        }

        /// <summary>
        /// Tao ngon ngu dang co trong portal
        /// </summary>
        /// <param name="rpt">
        /// _ID control se lap hien thi flag
        /// </param>

        #region Thuoc tinh tra ve duong dan web cho anh
        public string GetWebImageOfThumb(LocationImage lc, string filename) {

            string webpath = HomeDirectoryPortal;

            switch (lc)
            {
                case LocationImage.News:
                    webpath += "vc_project/NewsImgFolderOrg_thumb";
                    break;
                case LocationImage.Album:
                    webpath += "vc_project/AlbumImgFolderOrg_thumb";
                    break;
                case LocationImage.Slide:
                    webpath += "vc_project/SildeImgFolderOrg_thumb";
                    break;
                case LocationImage.Product:
                    webpath += "vc_project/ProductImgFolderOrg_thumb";
                    break;
                case LocationImage.Category:
                    webpath += "vc_project/CategoryImgFolderOrg_thumb";
                    break;
                default:
                    break;
            }

            return webpath + "/" + filename;

        }

        public string GetWebImgOf(LocationImage lc,string filename) {

            string webpath = HomeDirectoryPortal;

            switch (lc)
            {
                case LocationImage.News:
                    webpath += "vc_project/NewsImgFolderOrg";
                    break;
                case LocationImage.Album:
                    webpath += "vc_project/AlbumImgFolderOrg";
                    break;
                case LocationImage.Slide:
                    webpath += "vc_project/SildeImgFolderOrg";
                    break;
                case LocationImage.Product:
                    webpath += "vc_project/ProductImgFolderOrg";
                    break;
                case LocationImage.Category:
                    webpath+= "vc_project/CategoryImgFolderOrg";
                    break;
                default:
                    break;
            }

            return webpath + "/" + filename ;
        }

        public string FixLeng(string input,int leng) {

            return input.Substring(0,leng-4)+"...";
        
        }

        #endregion

        #region Lưu ảnh vào hệ thống


        /// <summary>
        /// Luu file anh vao he thong
        /// </summary>
        /// <param name="fl">Luong file can luu tru</param>
        /// <param name="filename">Ten file ban dau</param>
        /// <returns>Ten file thuc te tren he thong thu muc vat ly</returns>
        public string SaveImage(Stream stream, string _filename, LocationImage lc)
        {
            string pathFile = "", pathFileThumb = "";

            string folderOrg = GetFolderName(lc),folderThumb=folderOrg+"_thumb";

            string filename = Guid.NewGuid() + _filename;
            pathFile = Path.Combine(folderOrg,filename);
            pathFileThumb = Path.Combine(folderThumb,filename);


            //tao thu muc neu chua co
            if (!Directory.Exists(folderOrg))
            {
                Directory.CreateDirectory(folderOrg);
            }
            if (!Directory.Exists(folderThumb))
            {
                Directory.CreateDirectory(folderThumb);
            }
            //tao file goc

            if (stream.Length == 0) return "";

            // Create a FileStream object to write a stream to a file
            using (FileStream fileStream = System.IO.File.Create(pathFile, (int)stream.Length))
            {
                // Fill the bytes[] array with the stream data
                byte[] bytesInStream = new byte[stream.Length];
                stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
                // Use FileStream object to write to the specified file
                fileStream.Write(bytesInStream, 0, bytesInStream.Length);
            }
            //tao file da convert dang thum va luu
            SaveImageThumb(pathFile,pathFileThumb);
            return filename;
        }

        private  string GetFolderName(LocationImage lc)
        {
            string foldernamePath = "";

            switch (lc)
            {
                case LocationImage.News:
                    foldernamePath = "vc_project\\NewsImgFolderOrg";
                    break;
                case LocationImage.Album:
                    foldernamePath = "vc_project\\AlbumImgFolderOrg";
                    break;
                case LocationImage.Slide:
                    foldernamePath = "vc_project\\SildeImgFolderOrg";
                    break;
                case LocationImage.Product:
                    foldernamePath = "vc_project\\ProductImgFolderOrg";
                    break;
                case LocationImage.Category:
                    foldernamePath = "vc_project\\CategoryImgFolderOrg";
                    break;
                default:
                    break;
            }

            return Path.Combine(HomeDirectoryPortalFolder, foldernamePath);
        }


        public void DeleteNewsImage(string filename, LocationImage lc)
        {
            string pathFile = "", pathFileThumb = "";

            string folderOrg = GetFolderName(lc), folderThumb = folderOrg + "_thumb";

            pathFile = Path.Combine(folderOrg, filename);
            pathFileThumb = Path.Combine(folderThumb, filename);

            if (File.Exists(pathFile)) File.Delete(pathFile);
            if (File.Exists(pathFileThumb)) File.Delete(pathFileThumb);
        }

        private void SaveImageThumb(string pathFileSource, string pathFileDes)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(pathFileSource);
            System.Drawing.Image thumbnailImage = image.GetThumbnailImage(250, (image.Size.Height*250) / image.Size.Width, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
            MemoryStream imageStream = new MemoryStream();
            thumbnailImage.Save(pathFileDes, System.Drawing.Imaging.ImageFormat.Png);
        }

        /// <summary>
        /// Required, but not used
        /// </summary>
        /// <returns>true</returns>
        public bool ThumbnailCallback()
        {
            return true;
        }
        #endregion

    }
}
